/**
 * 安全评估证明材料收集系统类型定义
 */

// 评估模块类型
export interface EvaluationModule {
  id: string;
  name: string;
  description?: string;
  category: string;
  priority: 'high' | 'medium' | 'low';
  created_at: string;
  updated_at?: string;
}

// 查验点类型
export interface CheckPoint {
  id: string;
  name: string;
  description?: string;
  module_id: string;
  requirements: string[];
  created_at: string;
  updated_at?: string;
}

// 评估项元数据
export interface EvaluationMetadata {
  source_file: string;
  generated_at: string;
  version: string;
}

// 评估项类型
export interface EvaluationItem {
  id: string;
  module: string;
  category: string;
  checkpoint: string;
  materials: string[];
  notes: string;
  selected?: boolean;
  updated_at?: string;
}

// 文件上传状态
export type UploadStatus = 'idle' | 'uploading' | 'parsing' | 'completed' | 'error';

// 页面范围类型
export interface PageRange {
  startPage: number;
  endPage: number;
  totalPages?: number;
  mode: 'all' | 'range';
}

// 上传文件信息
export interface UploadedFile {
  id: string;
  name: string;
  size: number;
  type: string;
  status: UploadStatus;
  progress?: number;
  error_message?: string;
  uploaded_at: string;
  pageRange?: PageRange;
}

// AI 解析结果
export interface AIAnalysisResult {
  id: string;
  file_id: string;
  evaluation_items: EvaluationItem[];
  summary: {
    total_items: number;
    modules_count: number;
    checkpoints_count: number;
  };
  analysis_status: 'pending' | 'completed' | 'failed';
  created_at: string;
}

// AI 调整指令类型
export interface AIAdjustmentCommand {
  id: string;
  command: string;
  type: 'merge' | 'add' | 'remove' | 'modify';
  executed: boolean;
  rolledBack?: boolean; // 标记是否被撤销
  result?: string;
  created_at: string;
}

// 导出格式类型
export type ExportFormat = 'word' | 'excel';

// 导出配置
export interface ExportConfig {
  format: ExportFormat;
  include_notes: boolean;
  include_summary: boolean;
  selected_items_only: boolean;
}

// 统计信息
export interface Statistics {
  total_items: number;
  modules_count: number;
  important_items: number;
  exported_items: number;
}

// 表格排序配置
export interface SortConfig {
  field: keyof EvaluationItem;
  direction: 'asc' | 'desc';
}

// 表格过滤配置
export interface FilterConfig {
  module?: string;
  category?: string;
  selected_only?: boolean;
  search_term?: string;
}

// 页面状态
export interface ProofMapperState {
  // 文件上传相关
  uploadedFiles: UploadedFile[];
  currentFile: UploadedFile | null;
  
  // 评估项相关
  evaluationItems: EvaluationItem[];
  selectedItems: string[];
  
  // AI 相关
  analysisResult: AIAnalysisResult | null;
  adjustmentCommands: AIAdjustmentCommand[];
  aiInputValue: string;
  
  // 表格相关
  sortConfig: SortConfig;
  filterConfig: FilterConfig;
  
  // 导出相关
  exportConfig: ExportConfig;
  
  // 统计信息
  statistics: Statistics;
  
  // UI 状态
  loading: boolean;
  error: string | null;

  // 版本状态
  isVersionSaved: boolean; // 当前是否已保存为版本（且之后未修改）
  lastSavedVersionName?: string; // 最近一次保存的版本名
  versionHistory: VersionMeta[]; // 历史版本元数据列表
}

// 操作类型
export type ProofMapperAction =
  | { type: 'SET_LOADING'; payload: boolean }
  | { type: 'SET_ERROR'; payload: string | null }
  | { type: 'ADD_FILE'; payload: UploadedFile }
  | { type: 'DELETE_FILE'; payload: string }
  | { type: 'UPDATE_FILE_STATUS'; payload: { id: string; status: UploadStatus; progress?: number; pageRange?: PageRange } }
  | { type: 'SET_EVALUATION_ITEMS'; payload: EvaluationItem[] }
  | { type: 'UPDATE_EVALUATION_ITEM'; payload: EvaluationItem }
  | { type: 'DELETE_EVALUATION_ITEM'; payload: string }
  | { type: 'ADD_EVALUATION_ITEM'; payload: EvaluationItem }
  | { type: 'TOGGLE_ITEM_SELECTION'; payload: string }
  | { type: 'SET_SELECTED_ITEMS'; payload: string[] }
  | { type: 'SET_ANALYSIS_RESULT'; payload: AIAnalysisResult }
  | { type: 'ADD_ADJUSTMENT_COMMAND'; payload: AIAdjustmentCommand }
  | { type: 'SET_AI_INPUT'; payload: string }
  | { type: 'SET_SORT_CONFIG'; payload: SortConfig }
  | { type: 'SET_FILTER_CONFIG'; payload: FilterConfig }
  | { type: 'SET_EXPORT_CONFIG'; payload: ExportConfig }
  | { type: 'UPDATE_STATISTICS'; payload: Statistics }
  // 版本管理新增
  | { type: 'APPLY_SNAPSHOT'; payload: VersionSnapshot }
  | { type: 'ADD_VERSION_META'; payload: VersionMeta }
  | { type: 'MARK_DIRTY' };

// API 响应类型
export interface ApiResponse<T = any> {
  success: boolean;
  data?: T;
  message?: string;
  error?: string;
}

// 上传文件 API 响应
export interface UploadResponse extends ApiResponse {
  data: {
    file: UploadedFile;
    analysis_id: string;
  };
}

// AI 分析 API 响应
export interface AnalysisResponse extends ApiResponse {
  data: AIAnalysisResult;
}

// AI 调整 API 响应
export interface AdjustmentResponse extends ApiResponse {
  data: {
    updated_items: EvaluationItem[];
    command: AIAdjustmentCommand;
  };
}

// 导出 API 响应
export interface ExportResponse extends ApiResponse {
  data: {
    download_url: string;
    filename: string;
    format: ExportFormat;
  };
}

// 版本管理：元信息
export interface VersionMeta {
  id: string; // 单版本策略下可固定为 'latest' 或生成UUID，预留扩展
  name: string; // 用户自定义版本名
  saved_at: string; // ISO 时间戳
  items_count: number; // 评估项数量
  modules_count: number; // 模块数量
}

// 版本管理：快照（仅保存最近一次版本）
export interface VersionSnapshot {
  meta: VersionMeta;
  evaluationItems: EvaluationItem[];
  exportConfig: ExportConfig;
  statistics: Statistics;
}

// ===== Backend-aligned types for /proofmapper =====

// 与后端 EvaluationItem 字段一致的类型（包含可选的 selected/updated_at）
export interface BackendEvaluationItem {
  id: string;
  module: string;
  category: string;
  checkpoint: string;
  materials: string[];
  notes: string;
  selected?: boolean;
  updated_at?: string;
}

// 会话 shared 精简响应
export interface SharedResponse {
  final_output: {
    metadata: {
      source_file: string;
      generated_at: string; // ISO datetime
      version: string;
      interactive_modified?: boolean;
      modification_count?: number;
      last_modified_at?: string; // ISO datetime
    };
    items: BackendEvaluationItem[];
  };
  modification_log: Array<Record<string, any>>;
  error_log: string[];
}

// 快照响应（服务端会在查询时创建会话并返回 shared_id）
export interface SnapshotResponse {
  id: string;
  assessment_type: string;
  name: string;
  saved_at: string;
  evaluation_items: BackendEvaluationItem[];
  shared_id?: string;
}

// 快照列表响应
export interface SnapshotListResponse {
  snapshots: SnapshotResponse[];
  total: number;
}

// 创建快照请求体
export interface SnapshotCreate {
  assessment_type: string;
  name: string;
  evaluation_items: BackendEvaluationItem[];
}

// 更新快照请求体
export interface SnapshotUpdate {
  name?: string;
  evaluation_items?: BackendEvaluationItem[];
}
